package com.r2coding.article.api;

import com.r2coding.article.entity.MessageEntity;
import com.r2coding.article.feign.ThirdPartyFeignService;
import com.r2coding.article.model.SystemEmailReq;
import com.r2coding.article.service.MessageService;
import com.r2coding.common.constant.Constant;
import com.r2coding.common.enums.EmailType;
import com.r2coding.common.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author:98k灬
 * @since:2022/06/04 0:40
 **/
@RestController
@RequestMapping("/api/message")
public class ApiMessageController {
    @Autowired
    MessageService messageService;

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    /**
     * 获取全部的留言信息
     *
     * @return 统一响应体
     */
    @GetMapping("/getAll")
    public Result getAll() {
        List<MessageEntity> list = messageService.list();
        return Result.ok(list);
    }

    /**
     * 保存留言信息
     *
     * @param message 留言内容
     * @return 统一响应体
     */
    @PostMapping("/save")
    public Result save(@RequestBody MessageEntity message) {
        message.setCreateTime(new Date());
        message.setTime("Math.floor(Math.random() * 10 + 6)");
        messageService.save(message);
        // 給管理员发送邮件
        sendEmailToAdmin(message.getMessage());
        return Result.ok();
    }

    public void sendEmailToAdmin(String message) {
        SystemEmailReq req = new SystemEmailReq();
        req.setEmail(Constant.ADMIN_EMAIL);
        req.setEmailType(EmailType.MESSAGE_ADMIN);
        req.setOpinionType(message);
        thirdPartyFeignService.sendSystemEmail(req);
    }

    /**
     * 获取留言数量
     *
     * @return 留言数量
     */
    @GetMapping("/getMessageCount")
    public Integer getMessageCount() {
        return messageService.count();
    }
}
